#include "telemetrydialog.h"
#include "MessageBox.h"
#include "models/robot.h"
#include "qpainter.h"
#include "ui_telemetrydialog.h"

#include <models/robotlist.h>
#include <models/syssettingmodel.h>

#include <MainWindow.h>
#include <QFileDialog>
#include <QRadioButton>
#include <urdfwidget.h>

#include <QDesktopServices>
#include "models/sshclient.h"

TelemetryDialog::TelemetryDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::TelemetryForm)
    , m_bPressed(false) // 初始化拖动状态为 false
{
    setWindowFlags(Qt::Dialog|Qt::FramelessWindowHint | Qt::NoDropShadowWindowHint);
    setAttribute(Qt::WA_StyledBackground, true);
    ui->setupUi(this);
    Robot * pCurRobot = RobotList::getInstance()->getCurRobot();
        if(pCurRobot)
        {
            ui->telemetry_btn->setText("开始数采");
            ui->time_slider->setValue(60);
            ui->progressBar->setValue(0);
            ui->result_lab->setText("");
            connect(pCurRobot,&Robot::telemetryChanged, this,[=](bool bTelemetry){
                ui->telemetry_btn->setText(bTelemetry?"停止数采":"开始数采");
                ui->telemetry_btn->setChecked(bTelemetry);
                if(bTelemetry)
                {
                    m_timer.start(1000);
                    connect(&m_timer,&QTimer::timeout,this,&TelemetryDialog::onTimer,Qt::UniqueConnection);
                    ui->progressBar->setRange(0,ui->time_slider->value());
                    ui->progressBar->setValue(0);
                    connect(pCurRobot,&Robot::telemetryResult,this,&TelemetryDialog::onTelemetryResult,Qt::UniqueConnection);
                }
                ui->telemetry_btn->setEnabled(true);
            });
            connect(pCurRobot,&Robot::telemetryWSError,this,[=]{this->hide();});
        }
    scaleWidgets(this,g_xScale,g_yScale);
}

TelemetryDialog::~TelemetryDialog()
{
    delete ui;
}

void TelemetryDialog::scaleWidgets(QWidget *widget, double xScale,double yScale)
{
    setFixedSize(int(widget->width() * xScale), int(widget->height() * yScale));
    for (QWidget *child : widget->findChildren<QWidget*>()) {
        QRect geom = child->geometry();

            int width = qMax(1, static_cast<int>(int(geom.width() * xScale)));
            //当按钮高度比较大时使用y方向比例，当按钮比较小时使用x比例，防止按钮被压扁
            int height = qMax(1, static_cast<int>((geom.height() == geom.width() ? int(geom.height() * xScale) : int(geom.height() * yScale))));
            child->setFixedSize(width,height);
            child->move(int(geom.left() * xScale),int(geom.top() * yScale));
            QFont font = child->font();
            if(font.pixelSize()> 0)
                font.setPixelSize(int(font.pixelSize()*xScale));
            else if(font.pointSize()> 0)
                font.setPixelSize(int(font.pointSize()*xScale));
            child->setFont(font);
    }
}

void TelemetryDialog::showEvent(QShowEvent *event)
{
    Q_UNUSED(event)
    Robot * pCurRobot = RobotList::getInstance()->getCurRobot();
    if(pCurRobot)
    {
        QString strErr;
        pCurRobot->connectTelemetryWS(strErr);
    }
}

void TelemetryDialog::hideEvent(QHideEvent *event)
{
    Q_UNUSED(event)
    Robot * pCurRobot = RobotList::getInstance()->getCurRobot();
    if(pCurRobot)
    {
        pCurRobot->disConnectTelemetryWS();
    }
}
void TelemetryDialog::on_time_slider_valueChanged(int value)
{
    ui->time_lab->setText(QString("%1s").arg(value));
}


void TelemetryDialog::on_telemetry_btn_clicked()
{
    int nSecond = ui->time_slider->value();
    if(nSecond == 0)
    {
        warning(MainWindow::getInstance(),"数采时间必须大于0！");
        ui->telemetry_btn->setChecked(!ui->telemetry_btn->isChecked());
        return;
    }

    Robot* pCurRobot=RobotList::getInstance()->getCurRobot();
    if(pCurRobot)
    {
        if(ui->telemetry_btn->isChecked())
        {
            if(pCurRobot->startTelemetry())
                {
                ui->time_slider->setEnabled(false);
                ui->telemetry_btn->setEnabled(false);
                }
            else
            {
                warning(MainWindow::getInstance(),"启动数采失败！");
                }
            ui->progressBar->setValue(0);
        }
        else
            {
            if(pCurRobot->stopTelemetry())
            {
                ui->time_slider->setEnabled(true);
                ui->telemetry_btn->setEnabled(false);
            }
            else
            {
                warning(MainWindow::getInstance(),"停止数采失败！");
            }
            m_timer.stop();
            }
    }
    ui->telemetry_btn->setChecked(!ui->telemetry_btn->isChecked());
}


void TelemetryDialog::on_progressBar_valueChanged(int value)
{
    ui->progress_lab->setText(QString("%1/%2").arg(value).arg(ui->time_slider->value()));
}

void TelemetryDialog::onTimer()
{
    ui->progressBar->setValue(ui->progressBar->value()+1);
    if(ui->progressBar->value() == ui->time_slider->value())
    {
        Robot* pCurRobot=RobotList::getInstance()->getCurRobot();
        if(pCurRobot)
        {
            if(pCurRobot->stopTelemetry())
            {
                ui->time_slider->setEnabled(true);
                ui->telemetry_btn->setEnabled(false);
            }
        }
        m_timer.stop();
    }
}

void TelemetryDialog::onTelemetryResult(QString str)
{
    ui->result_lab->setText(str);
}

void TelemetryDialog::on_copy_btn_clicked()
{

    QString dir = QFileDialog::getExistingDirectory(this, tr("选择保存路径"), QDir::homePath());
    if (!dir.isEmpty())
    {
        Robot* pCurRobot = RobotList::getInstance()->getCurRobot();
         if (pCurRobot)
         {
            QString remoteFolder = SysSettingModel::getInstance()->strTelemetryFolder(); // 远程文件夹路径
             QString remoteUser = pCurRobot->strUser(); // 远程用户名
            QString password = pCurRobot->strPassword(); // 已知密码
             QString remoteHost = pCurRobot->strTelemetryIP(); // 远程主机地址
             QString localFolder = dir; // 本地文件夹
            // 使用libssh2拷贝远程文件夹到本地文件夹
             sshClient *copyClient = new sshClient();
             QThread *thread = new QThread;

             // Move the sshClient instance to the thread
             copyClient->moveToThread(thread);

             // Connect signals for success and error handling
             connect(copyClient, &sshClient::copyOK, this, [=]() {
                 // Open the local folder in the file explorer
                 QDesktopServices::openUrl(QUrl::fromLocalFile(localFolder));
                 // Clean up the thread and sshClient
                 thread->quit();
                 thread->wait();
                 copyClient->deleteLater();
                 thread->deleteLater();
                 ui->copy_btn->setEnabled(true);
             });

             connect(copyClient, &sshClient::copyError, this, [=](QString strErr) {
                 // Notify the user of the error
                 warning(MainWindow::getInstance(), strErr);
                 // Clean up the thread and sshClient
                 thread->quit();
                 thread->wait();
                 copyClient->deleteLater();
                 thread->deleteLater();
                 ui->copy_btn->setEnabled(true);
             });

             // Start the folder copy operation
             connect(thread, &QThread::started, [=]() {
                 copyClient->copyFolder(remoteHost, remoteUser, password, remoteFolder, localFolder);
             });

             // Start the thread
             thread->start();
             ui->copy_btn->setEnabled(false);
        }
    }
}

void TelemetryDialog::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        m_bPressed = true;
        m_dragStartPos = event->pos(); // 记录鼠标按下时的位置
        m_StartPos = this->pos(); // 记录按钮的初始位置
    }
    QDialog::mousePressEvent(event);
}

void TelemetryDialog::mouseMoveEvent(QMouseEvent *event)
{
    if (m_bPressed) {
        QPoint offset = event->pos() - m_dragStartPos; // 计算鼠标移动的偏移量
        QPoint newPos = m_StartPos + offset;     // 计算按钮的新位置

        // 限制按钮在父窗口范围内移动
        if (parentWidget()) {
            QRect parentRect = parentWidget()->rect();
            newPos.setX(qMax(0, qMin(newPos.x(), parentRect.width() - this->width())));
            newPos.setY(qMax(0, qMin(newPos.y(), parentRect.height() - this->height())));
        }

        move(newPos); // 移动按钮到新位置
        m_StartPos = newPos;
    }
}

void TelemetryDialog::mouseReleaseEvent(QMouseEvent *event)
{
        QDialog::mouseReleaseEvent(event);
    if (event->button() == Qt::LeftButton) {
        m_bPressed = false; // 停止拖动
    }
}

void TelemetryDialog::on_close_btn_clicked()
{
    this->hide();
}

